package com.example.airobotinterviewrecord.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.airobotinterviewrecord.entity.InterviewRecord;
import com.example.airobotinterviewrecord.mapper.InterviewRecordMapper;
import com.example.airobotinterviewrecord.service.IInterviewRecordService;
import com.example.candiates.service.InterviewCandidatesService;
import com.example.airobotpositions.service.IInterviewPositionsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 面试记录表 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-04-07
 */
@Service
public class InterviewRecordServiceImpl extends ServiceImpl<InterviewRecordMapper, InterviewRecord> implements IInterviewRecordService {
    private static final Logger logger = LoggerFactory.getLogger(InterviewRecordServiceImpl.class);

    // 状态常量定义
    private static final int STATUS_NOT_PASSED = 1;  // 未通过
    private static final int STATUS_PASSED = 2;      // 通过
    private static final int STATUS_PENDING = 3;     // 待定

    @Autowired
    private InterviewCandidatesService candidatesService;
    
    @Autowired
    private IInterviewPositionsService positionsService;

    @Override
    public IPage<InterviewRecord> listRecordsByPage(int pageNum, int pageSize) {
        Page<InterviewRecord> page = new Page<>(pageNum, pageSize);
        return this.page(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addRecord(InterviewRecord record) {
        try {
            logger.info("开始添加面试记录: {}", record);
            
            // 验证候选人是否存在
            if (record.getCandidateId() != null) {
                boolean candidateExists = candidatesService.getById(record.getCandidateId()) != null;
                if (!candidateExists) {
                    logger.error("候选人不存在, ID: {}", record.getCandidateId());
                    throw new IllegalArgumentException("候选人不存在");
                }
            }
            
            // 验证职位是否存在
            if (record.getPositionId() != null) {
                boolean positionExists = positionsService.getById(record.getPositionId()) != null;
                if (!positionExists) {
                    logger.error("职位不存在, ID: {}", record.getPositionId());
                    throw new IllegalArgumentException("职位不存在");
                }
            }
            
            // 验证状态值是否有效
            if (record.getStatus() != null) {
                if (record.getStatus() != STATUS_NOT_PASSED && 
                    record.getStatus() != STATUS_PASSED && 
                    record.getStatus() != STATUS_PENDING) {
                    logger.error("无效的状态值: {}", record.getStatus());
                    throw new IllegalArgumentException("状态值必须为：1(未通过)、2(通过)或3(待定)");
                }
            } else {
                // 设置默认状态为待定
                record.setStatus(STATUS_PENDING);
            }
            
            // 验证评分范围
            if (record.getScore() != null && (record.getScore() < 1 || record.getScore() > 100)) {
                logger.error("评分超出范围: {}", record.getScore());
                throw new IllegalArgumentException("评分必须在1-100之间");
            }
            
            // 验证评语长度
            if (record.getComments() != null && record.getComments().length() > 255) {
                logger.error("评语超出长度限制");
                throw new IllegalArgumentException("评语长度不能超过255个字符");
            }
            
            // 验证数字人面试官ID
            if (record.getDigitalInterviewerId() == null) {
                logger.error("数字人面试官ID不能为空");
                throw new IllegalArgumentException("数字人面试官ID不能为空");
            }
            
            boolean saved = save(record);
            if (saved) {
                logger.info("面试记录添加成功, ID: {}", record.getId());
                return "添加成功";
            } else {
                logger.error("面试记录添加失败");
                throw new RuntimeException("添加失败");
            }
        } catch (Exception e) {
            logger.error("添加面试记录时发生错误: ", e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteRecordById(Integer id) {
        try {
            logger.info("开始删除面试记录, ID: {}", id);
            
            if (id == null) {
                logger.error("删除ID为空");
                throw new IllegalArgumentException("ID不能为空");
            }
            
            InterviewRecord existing = getById(id);
            if (existing == null) {
                logger.error("记录不存在, ID: {}", id);
                throw new IllegalArgumentException("记录不存在");
            }
            
            boolean removed = removeById(id);
            if (!removed) {
                logger.error("删除记录失败, ID: {}", id);
                throw new RuntimeException("删除失败");
            }
            
            logger.info("面试记录删除成功, ID: {}", id);
            return "删除成功";
        } catch (Exception e) {
            logger.error("删除面试记录时发生错误: ", e);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateRecord(InterviewRecord record) {
        try {
            logger.info("开始更新面试记录: {}", record);
            
            if (record == null || record.getId() == null) {
                logger.error("更新记录ID为空");
                throw new IllegalArgumentException("Id不能为空");
            }
            
            // 验证记录是否存在
            InterviewRecord existing = getById(record.getId());
            if(existing == null) {
                logger.error("记录不存在, ID: {}", record.getId());
                throw new IllegalArgumentException("记录不存在");
            }

            // 验证候选人是否存在
            if (record.getCandidateId() != null) {
                boolean candidateExists = candidatesService.getById(record.getCandidateId()) != null;
                if (!candidateExists) {
                    logger.error("候选人不存在, ID: {}", record.getCandidateId());
                    throw new IllegalArgumentException("候选人不存在");
                }
            } else {
                // 如果未提供候选人ID，使用原记录的候选人ID
                record.setCandidateId(existing.getCandidateId());
            }
            
            // 验证职位是否存在
            if (record.getPositionId() != null) {
                boolean positionExists = positionsService.getById(record.getPositionId()) != null;
                if (!positionExists) {
                    logger.error("职位不存在, ID: {}", record.getPositionId());
                    throw new IllegalArgumentException("职位不存在");
                }
            } else {
                // 如果未提供职位ID，使用原记录的职位ID
                record.setPositionId(existing.getPositionId());
            }
            
            // 验证状态值是否有效
            if (record.getStatus() != null) {
                if (record.getStatus() != STATUS_NOT_PASSED && 
                    record.getStatus() != STATUS_PASSED && 
                    record.getStatus() != STATUS_PENDING) {
                    logger.error("无效的状态值: {}", record.getStatus());
                    throw new IllegalArgumentException("状态值必须为：1(未通过)、2(通过)或3(待定)");
                }
            } else {
                // 如果未提供状态，使用原记录的状态
                record.setStatus(existing.getStatus());
            }
            
            // 验证评分范围
            if (record.getScore() != null) {
                if (record.getScore() < 1 || record.getScore() > 10) {
                    logger.error("评分超出范围: {}", record.getScore());
                    throw new IllegalArgumentException("评分必须在1-10之间");
                }
            } else {
                // 如果未提供评分，使用原记录的评分
                record.setScore(existing.getScore());
            }
            
            // 验证评语长度
            if (record.getComments() != null) {
                if (record.getComments().length() > 255) {
                    logger.error("评语超出长度限制");
                    throw new IllegalArgumentException("评语长度不能超过255个字符");
                }
            } else {
                // 如果未提供评语，使用原记录的评语
                record.setComments(existing.getComments());
            }

            // 验证数字人面试官ID
            if (record.getDigitalInterviewerId() == null) {
                logger.error("数字人面试官ID不能为空");
                throw new IllegalArgumentException("数字人面试官ID不能为空");
            }

            // 保持原有的创建时间
            record.setCreatedAt(existing.getCreatedAt());
            
            boolean updated = updateById(record);
            if (!updated) {
                logger.error("更新记录失败, ID: {}", record.getId());
                throw new RuntimeException("更新失败");
            }
            
            logger.info("面试记录更新成功, ID: {}", record.getId());
            return "更新成功";
        } catch (Exception e) {
            logger.error("更新面试记录时发生错误: ", e);
            throw e;
        }
    }

    @Override
    public List<InterviewRecord> getRecordsByDigitalInterviewerId(Integer digitalInterviewerId) {
        return baseMapper.selectByDigitalInterviewerId(digitalInterviewerId);
    }
}
